#include "AudioPlay.h"

AudioPlay::AudioPlay( ) : m_soundCounter(0) 
{
	result = FMOD::System_Create(&system);		// Create the main system object.
	if (result != FMOD_OK)
	{
		printf("FMOD error! (%d) %s\n", result, FMOD_ErrorString(result));
		exit(-1);
	}

	result = system->init(100, FMOD_INIT_NORMAL, 0);	// Initialize FMOD.
	if (result != FMOD_OK)
	{
		printf("FMOD error! (%d) %s\n", result, FMOD_ErrorString(result));
		exit(-1);
	}
	
	//initialize.
	result = system->getVersion(&version);
	if (version < FMOD_VERSION)
	{
		printf("Error! You are using an old version of FMOD %08x. This program requires %08x\n", version, FMOD_VERSION);
		return ;
	}

	result = system->getNumDrivers(&numdrivers);
	if (numdrivers == 0)
	{
		result = system->setOutput(FMOD_OUTPUTTYPE_NOSOUND);
	}
	else
	{
		result = system->getDriverCaps(0, &caps, 0, &speakermode);

		//Set the user selected speaker mode.
		result = system->setSpeakerMode(speakermode);
		if (caps & FMOD_CAPS_HARDWARE_EMULATED)
		{
			result = system->setDSPBufferSize(1024, 10);
		}
		result = system->getDriverInfo(0, name, 256, 0);
		if (strstr(name, "SigmaTel"))
		{
			
			//Sigmatel sound devices crackle for some reason if the format is PCM 16bit.
			//PCM floating point output seems to solve it.
			
			result = system->setSoftwareFormat(48000, FMOD_SOUND_FORMAT_PCMFLOAT, 0,0, FMOD_DSP_RESAMPLER_LINEAR);
		}
	}
	result = system->init(100, FMOD_INIT_NORMAL, 0);
	if (result == FMOD_ERR_OUTPUT_CREATEBUFFER)
	{
		
		//Switch it back to stereo...
		
		result = system->setSpeakerMode(FMOD_SPEAKERMODE_STEREO);
		
		//... and re-init.
		
		result = system->init(100, FMOD_INIT_NORMAL, 0);
	}

	// create a background music that loops
	//result = system->createSound("Title.mp3", FMOD_LOOP_NORMAL, 0, &music[TITLE]);
}

AudioPlay::~AudioPlay( )
{
	system->release( ) ;
}

void AudioPlay::updateAudio( )
{
	system->update( ) ;
}

void AudioPlay::playSound( )
{
	channel_sound->stop( ) ;
	system->playSound(FMOD_CHANNEL_FREE, m_sound, false, &channel_sound);
}